package com.retoc.graduationtravel.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.retoc.graduationtravel.Utils.SnowFlake;
import com.retoc.graduationtravel.common.ApiRestResponse;
import com.retoc.graduationtravel.common.Constant;
import com.retoc.graduationtravel.domain.Article;
import com.retoc.graduationtravel.domain.ArticleContent;
import com.retoc.graduationtravel.domain.ArticleImg;
import com.retoc.graduationtravel.domain.City;
import com.retoc.graduationtravel.domain.VO.ArticleVO;
import com.retoc.graduationtravel.domain.req.ArticleSaveReq;
import com.retoc.graduationtravel.exception.BusinessiException;
import com.retoc.graduationtravel.exception.ExceptionEnum;
import com.retoc.graduationtravel.service.ArticleContentService;
import com.retoc.graduationtravel.service.ArticleImgService;
import com.retoc.graduationtravel.service.ArticleService;
import com.retoc.graduationtravel.service.CityService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;

@RequestMapping("/article")
@RestController
public class ArticleController {

    @Autowired
    ArticleService articleService;

    @Autowired
    ArticleImgService articleImgService;

    @Autowired
    ArticleContentService articleContentService;

    @Autowired
    CityService cityService;

    @Autowired
    SnowFlake snowFlake;

    @GetMapping("/select")
    public ApiRestResponse<ArticleVO> selectArticle(@RequestParam("articleId") Long articleId) {
        Article article = articleService.getById(articleId);
        QueryWrapper<ArticleContent> qwContent = new QueryWrapper<>();
        qwContent.eq("article_id", articleId);
        ArticleContent content = articleContentService.getOne(qwContent);
        List<String> urlList = articleImgService.getUrlList(articleId);
        ArticleVO result = new ArticleVO();
        BeanUtils.copyProperties(article, result);
        result.setContent(content.getContent());
        result.setImg(urlList);
        City city = cityService.getById(article.getCityId());
        result.setCityName(city.getName());
        return ApiRestResponse.success(result);
    }

    @PostMapping("/save")
    public ApiRestResponse<Boolean> updateArticle(@Valid @RequestBody ArticleSaveReq articleSaveReq) {
        //新增文章
        if (articleSaveReq.getId() == null) {
            //向数据库写入article基本信息
            Article article = new Article();
            BeanUtils.copyProperties(articleSaveReq, article);
            Long articleId = snowFlake.nextId();
            article.setId(articleId);
            article.setDate(new Date());
            Document doc = Jsoup.parse(articleSaveReq.getContent());
            Element img = doc.select("img").first();
            String imgUrl = "";
            if (img != null) {
                imgUrl = img.attr("src");
            } else {
                imgUrl = null;
            }
            article.setImgUrl(imgUrl);
            boolean save1 = articleService.save(article);
            //向数据库写入article关联图片信息
            Elements imgs = doc.select("img");
            List<String> srcs = imgs.eachAttr("src");
            for (int i = 0; i < srcs.size(); i++) {
                ArticleImg articleImg = new ArticleImg();
                articleImg.setArticleId(articleId);
                articleImg.setImgUrl(srcs.get(i));
                articleImgService.save(articleImg);
            }
            //向数据库写入article内容信息
            ArticleContent articleContent = new ArticleContent();
            articleContent.setArticleId(articleId);
            articleContent.setContent(articleSaveReq.getContent());
            boolean save2 = articleContentService.save(articleContent);
            return ApiRestResponse.success(save1 && save2);
        }
        //修改文章
        else {
            Article article = new Article();
            BeanUtils.copyProperties(articleSaveReq, article);
            Document doc = Jsoup.parse(articleSaveReq.getContent());
            Element img = doc.select("img").first();
            String imgUrl = "";
            if (img != null) {
                imgUrl = img.attr("src");
            } else {
                imgUrl = null;
            }
            article.setImgUrl(imgUrl);
            boolean b = articleService.saveOrUpdate(article);
            //向数据库写入article关联图片信息
            //先清空该文章图片数据再添加
            QueryWrapper<ArticleImg> qw = new QueryWrapper<>();
            qw.eq("article_id", articleSaveReq.getId());
            articleImgService.remove(qw);
            Elements imgs = doc.select("img");
            List<String> srcs = imgs.eachAttr("src");
            for (String src : srcs) {
                ArticleImg articleImg = new ArticleImg();
                articleImg.setArticleId(articleSaveReq.getId());
                articleImg.setImgUrl(src);
                articleImgService.save(articleImg);
            }
            //向数据库写入article内容信息
            QueryWrapper<ArticleContent> qwc = new QueryWrapper<>();
            qwc.eq("article_id", articleSaveReq.getId());
            articleContentService.remove(qwc);
            ArticleContent articleContent = new ArticleContent();
            articleContent.setArticleId(articleSaveReq.getId());
            articleContent.setContent(articleSaveReq.getContent());
            articleContentService.save(articleContent);
            return ApiRestResponse.success();
        }
    }

    @PostMapping("upload")
    @ResponseBody
    public Map upload(@RequestParam("img") MultipartFile file, HttpServletRequest request) {
        String filename = file.getOriginalFilename();
        assert filename != null;
        String suffixName = filename.substring(filename.lastIndexOf("."));
        String newFileName = UUID.randomUUID() + suffixName;
        File fileDirectory = new File(Constant.FILE_UPLOAD_DIR);
        File destFile = new File(Constant.FILE_UPLOAD_DIR + newFileName);
        if (!fileDirectory.exists()) {
            if (fileDirectory.mkdir()) {
                throw new BusinessiException(ExceptionEnum.MKDIR_FAIL);
            }
        }
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Map result = new HashMap();
        try {
            String fileURI = getHost(new URI(request.getRequestURL() + "")) + "/images/" + newFileName;
            result.put("errno", 0);
            Map dataMap = new HashMap();
            dataMap.put("url", fileURI);
//            dataMap.put("alt",newFileName);
            result.put("data", dataMap);
            return result;
        } catch (URISyntaxException e) {
            result.put("errno", 1);
            result.put("message", "上传失败");
            return result;
        }
    }

    private URI getHost(URI uri) {
        URI effectiveURI;
        try {
            effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null);
        } catch (URISyntaxException e) {
            effectiveURI = null;
        }
        return effectiveURI;
    }
}
